package org.jeecgframework.web.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyEquipmentSpareServiceI;
import org.jeecgframework.web.service.ZyTimeTaskForWarrantyPeriodSevice;
import org.jeecgframework.web.service.ZyWarrantyPeriodServiceI;
import org.jeecgframework.web.system.pojo.base.ZyEquipmentSpareEntity;
import org.jeecgframework.web.system.pojo.base.ZyFileLogEntity;
import org.jeecgframework.web.system.pojo.base.ZyUpWarrantyPeriodCheckSnThread;
import org.jeecgframework.web.system.pojo.base.ZyWarrantyPeriodCEntity;
import org.jeecgframework.web.system.pojo.base.ZyWarrantyPeriodEntity;
import org.jeecgframework.web.system.pojo.base.ZyWarrantyPeriodHEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.FileBean;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.web.util.UploadFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Title: Controller
 * @Description: 保期记录历史
 * @author ZhangYunlong
 * @date 2016-04-17 12:00:24
 * @version V1.0
 * 
 */
@Scope("prototype")
@Controller
@RequestMapping("/zyWarrantyPeriodController")
public class ZyWarrantyPeriodController extends BaseController {

	@Autowired
	private ZyWarrantyPeriodServiceI zyWarrantyPeriodService;
	@Autowired
	private ZyEquipmentSpareServiceI zyEquipmentSpareService;
	@Autowired
	private ZyCommonService zyCommonService;
	@Autowired
	private SystemService systemService;
	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	/**
	 * 保期记录列表 页面跳转
	 */
	@RequestMapping(params = "zyWarrantyPeriod")
	public ModelAndView zyWarrantyPeriod(HttpServletRequest request) {
		return new ModelAndView("com/zybk/zy_upload_warranty_record/zyWarrantyPeriodList");
	}

	/**
	 * 保期记录 datagrid
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "datagrid")
	public void datagrid(ZyWarrantyPeriodEntity zyWarrantyPeriod, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ZyWarrantyPeriodEntity.class, dataGrid);
		String sn = request.getParameter("sn");
		if (null != sn && !sn.equals("")) {
			cq.eq("sn", sn);
		}
		// 查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyWarrantyPeriod, request.getParameterMap());
		try {
			// 自定义追加查询条件
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.zyWarrantyPeriodService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 保期记录历史列表 页面跳转
	 */
	@RequestMapping(params = "zyWarrantyPeriodHis")
	public ModelAndView zyWarrantyPeriodHis(HttpServletRequest request) {
		return new ModelAndView("com/zybk/zy_upload_warranty_record/zyWarrantyPeriodListHis");
	}

	/**
	 * 保期记录历史列表 datagrid
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "datagridForHistory")
	public void datagridForHistory(ZyWarrantyPeriodHEntity zyWarrantyPeriodH, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ZyWarrantyPeriodHEntity.class, dataGrid);
		// 查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyWarrantyPeriodH, request.getParameterMap());
		try {
			// 自定义追加查询条件
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.zyWarrantyPeriodService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * @author xiul 2016-6-29 上午11:33:47 Description 导入保期记录 跳转
	 */
	@RequestMapping(params = "uploadFile")
	public ModelAndView uploadFile(HttpServletRequest request) {
		return new ModelAndView("com/zybk/file_upload/uploadWarrantyPeriod");
	}

	/**
	 * @author xiul 2016-6-29 上午11:48:49 Description 保存上传的文件
	 */
	@ResponseBody
	@RequestMapping(params = "importExcel")
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		FileBean fileBean = UploadFileUtil.UploadFile(request);
		ZyFileLogEntity fileLog = new ZyFileLogEntity();
		fileLog.setBusinessType(StaticValue.IMPORT_FILE_PERIOD_RECORDER); // 文件业务
		fileLog.setOldFileName(fileBean.getFileRealName());// 文件原名
		fileLog.setNewFileName(fileBean.getFileName());// 文件新名
		fileLog.setFilePath(fileBean.getSavePath());
		fileLog.setFileType("xlsx");
		fileLog.setStatus("0");
		systemService.save(fileLog);
		j.setObj(fileLog);
		return j;
	}

	/**
	 * @author xiul 2016-6-29 上午11:49:00 Description 读取上传的excel
	 */
	@RequestMapping(params = "checkExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson checkExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		boolean flag = true;
		message = "导入成功";
		System.out.println("进入保期记录导入 Action");
		long begin = System.currentTimeMillis();
		try {
			int total = zyCommonService.getCountBySql("select count(1) total from zy_warranty_period_c t where t.status = '0'");
			if (total == 0) {
				List<String> snList = zyWarrantyPeriodService.parseExcel(request);
				String repeatSn = null;
				int maxUnit = 2000;
				int countRow = snList.size();
				if (countRow > maxUnit) {
					int threadC = countRow % maxUnit > 0 ? countRow / maxUnit + 1 : countRow / maxUnit;
					System.out.println("threadC:" + threadC);
					System.out.println("snList:" + snList.size());
					ThreadPoolExecutor exec = (ThreadPoolExecutor) Executors.newFixedThreadPool(threadC);
					ArrayList<Future<String>> results = new ArrayList<Future<String>>();
					for (int i = 0; i < threadC; i++) {
						int beginR = i * maxUnit;
						int endR = i == (threadC - 1) ? beginR + (countRow % maxUnit) - 1 : (beginR + maxUnit - 1);
						results.add(exec.submit(new ZyUpWarrantyPeriodCheckSnThread(snList, beginR, endR)));
					}
					do {
						for (Future<String> fs : results) {
							if (fs.isDone()) {
								if (StringUtil.isNotEmpty(fs.get())) {
									message = "SN：" + fs.get().trim() + "，重复";
									flag = false;
									break;
								}
							}
						}
					} while (exec.getCompletedTaskCount() < results.size() && flag);
					exec.shutdown();
				} else {
					repeatSn = zyWarrantyPeriodService.checkSnRepeat(snList, 0, snList.size() - 1);
					if (StringUtil.isNotEmpty(repeatSn)) {
						message = "SN：" + repeatSn.trim() + "，重复";
						flag = false;
					}
				}
			} else {
				String fileLogId = oConvertUtils.getString(request.getParameter("fileLogId"));
				ZyFileLogEntity fileLog = systemService.getEntity(ZyFileLogEntity.class, fileLogId);// 如过有差异数据未处理，此处的
																									// 上传记录应该删除，否则定时里会查出来并解析
				systemService.delete(fileLog);
				message = "请先处理差异数据";
				flag = false;
			}
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg(e.getMessage());
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		System.out.println("保期记录解析并比对 sn 完毕，用时：" + (end - begin) / 1000 + "." + (end - begin) % 1000 + "秒");
		j.setMsg(message);
		j.setSuccess(flag);
		return j;
	}

	/**
	 * @author ZhangYunlong 2016-4-18 下午6:00:15 Description 保修记录差异页面
	 *         differDatagrid
	 * @param zyInstallRecordCp
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "differDatagrid")
	public void differDatagrid(ZyWarrantyPeriodCEntity zyWarrantyPeriodC, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ZyWarrantyPeriodCEntity.class, dataGrid);
		// 查询条件组装器
		cq.eq("status", "0");
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyWarrantyPeriodC, request.getParameterMap());
		try {
			// 自定义追加查询条件
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.systemService.getDataGridReturn(cq, true);
		String temp = "";
		for (ZyWarrantyPeriodCEntity zyWarrantyPeriodCEntity : (List<ZyWarrantyPeriodCEntity>) dataGrid.getResults()) {
			temp = zyWarrantyPeriodCEntity.getVersion().substring(1);
			if (Float.valueOf(temp) % 2 == 0) {

				zyWarrantyPeriodCEntity.setFormFlag("2");
			}
			if (zyWarrantyPeriodCEntity.getType().equals("d") || zyWarrantyPeriodCEntity.getType().equals("i")) {
				zyWarrantyPeriodCEntity.setFormFlag("2");
			}
		}
		;
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * @author ZhangYunlong 2016-4-18 下午6:00:15 Description 保修记录差异页面
	 *         differHisDatagrid
	 * @param zyInstallRecordCp
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "differHisDatagrid")
	public void differHisDatagrid(ZyWarrantyPeriodCEntity zyWarrantyPeriodC, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ZyWarrantyPeriodCEntity.class, dataGrid);
		// 查询条件组装器
		cq.eq("status", "1");
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyWarrantyPeriodC, request.getParameterMap());
		try {
			// 自定义追加查询条件
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 更新安装记录
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doSetStatus")
	@ResponseBody
	public AjaxJson doSetStatus(ZyWarrantyPeriodCEntity zyWarrantyPeriodC, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "安装记录处理成功";
		zyWarrantyPeriodC = systemService.get(ZyWarrantyPeriodCEntity.class, zyWarrantyPeriodC.getId());
		List<ZyWarrantyPeriodCEntity> zyWarrantyPeriodCs = systemService.findByProperty(ZyWarrantyPeriodCEntity.class, "sn", zyWarrantyPeriodC.getSn());
		try {
			for (ZyWarrantyPeriodCEntity zyWarrantyPeriodCEntity : zyWarrantyPeriodCs) {
				zyWarrantyPeriodCEntity.setStatus("1");
				zyWarrantyPeriodService.saveOrUpdateForCp(zyWarrantyPeriodCEntity);
			}
			/*
			 * zyWarrantyPeriodC.setStatus("1");
			 * zyWarrantyPeriodService.saveOrUpdateForCp(zyWarrantyPeriodC);
			 */
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "安装记录处理失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * @author xiul 2016-4-19 下午5:57:10 Description 查看设备详细
	 * @param zyEquipmentSpare
	 * @param req
	 * @return mv
	 */
	@RequestMapping(params = "goView")
	public ModelAndView goView(ZyWarrantyPeriodCEntity zyWarrantyPeriodC, HttpServletRequest req) {
		if (zyWarrantyPeriodC.getSn() != null) {
			List<ZyEquipmentSpareEntity> zyEquipmentSpares = zyEquipmentSpareService.findByProperty(ZyEquipmentSpareEntity.class, "sn", zyWarrantyPeriodC.getSn());
			ZyEquipmentSpareEntity zyEquipmentSpare = null;
			if (zyEquipmentSpares.size() > 0) {
				zyEquipmentSpare = zyEquipmentSpares.get(0);
			}
            //根据设备sn号，查找最近一次维修的软件版本信息   2018/5/8添加
            String sql ="SELECT\n" +
                    "\tIFNULL(\n" +
                    "\t\tDATE_FORMAT(\n" +
                    "\t\t\tMAX(sc.create_date),\n" +
                    "\t\t\t'%Y-%m-%d'\n" +
                    "\t\t),\n" +
                    "\t\t''\n" +
                    "\t) AS vcreate_date,\n" +
                    "\tMAX(\n" +
                    "\t\tIFNULL(sc.REPAIR_AFTER1, '')\n" +
                    "\t) AS v1,\n" +
                    "\tMAX(\n" +
                    "\t\tIFNULL(sc.REPAIR_AFTER2, '')\n" +
                    "\t) AS v2\n" +
                    "FROM\n" +
                    "\tcbs_service cbs\n" +
                    "LEFT JOIN CBS_SCENE_REPORT sc ON sc.sn = cbs.sn\n" +
                    "WHERE cbs.sn = '"+zyEquipmentSpare.getSn()+"'";
            List<Map<String, Object>> list = systemService.findForJdbc(sql);
            if(list.size()>0){
                zyEquipmentSpare.setV1(list.get(0).get("v1").toString());  //放映机软件版本
                zyEquipmentSpare.setV2(list.get(0).get("v2").toString()); //ICP/TI/ICMP软件版本
                zyEquipmentSpare.setVcreateDate(list.get(0).get("vcreate_date").toString()); //版本更新时间
            }

			req.setAttribute("zyEquipmentSparePage", zyEquipmentSpare);
		}
		return new ModelAndView("com/zybk/zy_equipment_spare/zyEquipmentSpare-view");
	}

	/**
	 * 删除保期记录历史
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(ZyWarrantyPeriodEntity zyWarrantyPeriod, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		zyWarrantyPeriod = systemService.getEntity(ZyWarrantyPeriodEntity.class, zyWarrantyPeriod.getId());
		message = "保期记录历史删除成功";
		try {
			zyWarrantyPeriodService.delete(zyWarrantyPeriod);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "保期记录历史删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 批量删除保期记录历史
	 * 
	 * @return
	 */
	@RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "保期记录历史删除成功";
		try {
			for (String id : ids.split(",")) {
				ZyWarrantyPeriodEntity zyWarrantyPeriod = systemService.getEntity(ZyWarrantyPeriodEntity.class, id);
				zyWarrantyPeriodService.delete(zyWarrantyPeriod);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = "保期记录历史删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 添加保期记录历史
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(ZyWarrantyPeriodEntity zyWarrantyPeriod, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "保期记录历史添加成功";
		try {
			zyWarrantyPeriodService.save(zyWarrantyPeriod);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "保期记录历史添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 更新保期记录历史
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(ZyWarrantyPeriodEntity zyWarrantyPeriod, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "保期记录历史更新成功";
		ZyWarrantyPeriodEntity t = zyWarrantyPeriodService.get(ZyWarrantyPeriodEntity.class, zyWarrantyPeriod.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(zyWarrantyPeriod, t);
			zyWarrantyPeriodService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "保期记录历史更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 保期记录历史新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(ZyWarrantyPeriodEntity zyWarrantyPeriod, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zyWarrantyPeriod.getId())) {
			zyWarrantyPeriod = zyWarrantyPeriodService.getEntity(ZyWarrantyPeriodEntity.class, zyWarrantyPeriod.getId());
			req.setAttribute("zyWarrantyPeriodPage", zyWarrantyPeriod);
		}
		return new ModelAndView("com/buss/c/zyWarrantyPeriod-add");
	}

	/**
	 * 保期记录历史编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(ZyWarrantyPeriodEntity zyWarrantyPeriod, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zyWarrantyPeriod.getId())) {
			zyWarrantyPeriod = zyWarrantyPeriodService.getEntity(ZyWarrantyPeriodEntity.class, zyWarrantyPeriod.getId());
			req.setAttribute("zyWarrantyPeriodPage", zyWarrantyPeriod);
		}
		return new ModelAndView("com/buss/c/zyWarrantyPeriod-update");
	}

	/** -------------测试用------begin------- */
	@Autowired
	private ZyTimeTaskForWarrantyPeriodSevice zyTimeTaskForWarrantyPeriodSevice;

	/**
	 * @author xiul 2016-7-7 下午5:23:49 Description 方便测试，跑定时导入保期记录任务用
	 */
	@ResponseBody
	@RequestMapping(params = "runTimeTask")
	public void runTimeTask() {
		zyTimeTaskForWarrantyPeriodSevice.zyRecordImport();
	}
	/** -------------测试用-------end------ */
}
